/**
 * created by 小卷毛, 2021-07-21
 * Copyright (c) 2021, 416143467@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.rzico.sbl.viewmodel

import androidx.core.view.isVisible
import androidx.lifecycle.MutableLiveData
import com.lzg.extend.BaseResponse
import com.lzg.extend.JsonConvert
import com.lzg.okrx.RxSingleHelper
import com.lzg.okrx.adapter.FlowableBody
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.databinding.ActivityManualEditBinding
import com.rzico.sbl.databinding.ActivityManualRepairBinding
import com.rzico.sbl.model.AddressData
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.CommonData
import com.rzico.sbl.model.RecordData
import com.rzico.sbl.model.RecordFindData
import com.rzico.sbl.model.ResponseModel
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.extend.optNotNull
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.utils.applyFlowableSchedulers
import com.xinnuo.common_ui.utils.applySchedulers
import com.xinnuo.common_ui.utils.subscribeByFinally
import org.json.JSONObject

/**
 * 描 述：人工报单操作相关
 * 作 者：小卷毛  2021-07-21 15:55
 * 修改描述：
 * 修 改 人：
 * 修改版本：
 */
class ManualViewModel : CommonViewModel() {

    val mTicketEvent = MutableLiveData(0)
    val mPayEvent = MutableLiveData<ArrayList<CommonData>>()
    val mTotalEvent = MutableLiveData<Double>()

    /**
     * 收货列表
     */
    fun memberList(
        page: Int,
        keyWord: String,
        onSuccess: (ArrayList<AddressData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.post<BaseResponse<ResponseModel<AddressData>>>(BaseUrl.manuList)
            .isMultipart(true)
            .params(
                getParams(
                    "keyword" to keyWord,
                    "pageStart" to page * 10,
                    "pageSize" to 10
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<AddressData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 接单列表
     */
    fun callList(
        page: Int,
        onSuccess: (ArrayList<RecordData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) = mDisposables.add(
        OkGo.get<BaseResponse<ResponseModel<RecordData>>>(BaseUrl.manuCallLis)
            .params(
                getParams(
                    "pageStart" to page * 20,
                    "pageSize" to 20
                )
            )
            .converter(object : JsonConvert<BaseResponse<ResponseModel<RecordData>>>() {})
            .adapt(FlowableBody())
            .compose(applyFlowableSchedulers())
            .map { it.data.data }
            .subscribeByFinally(
                event = this,
                onSuccess = onSuccess,
                onFinally = onFinally
            )
    )

    /**
     * 根据手机查询会员信息
     */
    fun findMobile(
        phone: String,
        onSuccess: (ArrayList<RecordFindData>) -> Unit = {},
        onFinally: () -> Unit = {}
    ) =
        mDisposables.add(
            OkGo.get<BaseResponse<ArrayList<RecordFindData>>>(BaseUrl.manuCallFin)
                .params(
                    getParams("mobile" to phone)
                )
                .converter(object : JsonConvert<BaseResponse<ArrayList<RecordFindData>>>() {})
                .adapt(FlowableBody())
                .compose(applyFlowableSchedulers())
                .map { it.data }
                .subscribeByFinally(
                    event = this,
                    onSuccess = onSuccess,
                    onFinally = onFinally
                )
        )


    /**
     * 报单信息
     */
    fun manualInfo(
        receiverId: String,
        memberId: String,
        ticketEnable: Boolean,
    ) =
        RxSingleHelper.requestString(
            url = BaseUrl.manuInfo,
            params = getParams(
                "receiverId" to receiverId,
                "memberId" to memberId,
                "exchangeEnable" to ticketEnable
            )
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 添加商品 BaseUrl.manuAdd
     * 编辑商品 BaseUrl.manuEdt
     * 删除商品 BaseUrl.manuDel
     * 提交商品 BaseUrl.manuSub
     */
    fun goodsEdit(url: String, vararg params: Pair<String, Any>) =
        RxSingleHelper.requestString(
            url = url,
            isMultipart = true,
            params = getParams(*params)
        )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 商品列表
     */
    fun cartList() =
        RxSingleHelper
            .requestString(
                url = BaseUrl.manuCart,
                method = HttpMethod.GET
            )
            .compose(applySchedulers())
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }

    /**
     * 付款方式
     */
    fun getPayment() =
        requestCommon(
            isLoading = true,
            requestUrl = BaseUrl.manuWay,
            requestMethod = HttpMethod.GET,
            onSuccess = { mPayEvent.value = it }
        )

    /**
     * 会员水票信息
     */
    fun ticketCount(cardId: String) =
        requestCommon(
            requestUrl = BaseUrl.ticketCount,
            requestMethod = HttpMethod.GET,
            params = arrayOf(
                "cardId" to cardId,
                "subType" to "water"
            ),
            onSuccess = { list ->
                var ticketCount = 0
                list.forEach { ticketCount += it.stock.intValue }

                mTicketEvent.value = ticketCount
            }
        )

    /**
     * 商品合计
     */
    fun cartCount(
        receiverId: String,
        memberId: String,
        ticketEnable: Boolean,
        binding: ActivityManualEditBinding
    ) {
        request(
            requestUrl = BaseUrl.manuTotal,
            params = arrayOf(
                "receiverId" to receiverId,
                "memberId" to memberId,
                "pledge" to "0",
                "pledgeQuantity" to "0",
                "exchangeEnable" to ticketEnable
            ),
            onSuccess = { updatePrice(binding, JSONObject(it)) }
        )
    }

    /**
     * 更新收款金额
     */
    fun updatePrice(
        binding: ActivityManualEditBinding,
        obj: JSONObject
    ) {
        binding.apply {
            // 电子水票
            manualTicket.text = "–${
                obj.optNotNull("exchangeDiscount")
                    .also {
                        manualTicketLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 优惠券
            manualCoupon.text = "–${
                obj.optNotNull("couponDiscount")
                    .also {
                        manualCouponLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 金币
            manualCoin.text = "–${
                obj.optNotNull("pointDiscount")
                    .also {
                        manualCoinLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 会员余额抵扣
            manualVip.text = "–${
                obj.optNotNull("vipDiscount")
                    .also {
                        manualVipLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 运费
            manualFee.text = "+${
                obj.optNotNull("freight")
                    .also {
                        manualFeeLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 应收金额
            manualTotal.text =
                obj.optNotNull("amountPayable")
                    .also {
                        mTotalEvent.value = it.doubleValue
                    }.formatDecimal()

            // 上期欠款
            manualBefore.text =
                obj.optNotNull("arrears")
                    .also {
                        manualBeforeLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()

            // 上期欠票
            manualBefore1.text =
                obj.optNotNull("ticket")
                    .also {
                        manualBeforeLl1.isVisible = it.intValue > 0
                    }
        }
    }

    /**
     * 补单商品合计
     */
    fun cartCountFill(
        receiverId: String,
        memberId: String,
        ticketEnable: Boolean,
        binding: ActivityManualRepairBinding
    ) {
        request(
            requestUrl = BaseUrl.manuTotal,
            params = arrayOf(
                "receiverId" to receiverId,
                "memberId" to memberId,
                "pledge" to "0",
                "pledgeQuantity" to "0",
                "exchangeEnable" to ticketEnable
            ),
            onSuccess = { updatePriceFill(binding, JSONObject(it)) }
        )
    }

    /**
     * 更新补单收款金额
     */
    fun updatePriceFill(
        binding: ActivityManualRepairBinding,
        obj: JSONObject
    ) {
        binding.apply {
            // 电子水票
            manualTicket.text = "–${
                obj.optNotNull("exchangeDiscount")
                    .also {
                        manualTicketLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 优惠券
            manualCoupon.text = "–${
                obj.optNotNull("couponDiscount")
                    .also {
                        manualCouponLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 金币
            manualCoin.text = "–${
                obj.optNotNull("pointDiscount")
                    .also {
                        manualCoinLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 会员余额抵扣
            manualVip.text = "–${
                obj.optNotNull("vipDiscount")
                    .also {
                        manualVipLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 运费
            manualFee.text = "+${
                obj.optNotNull("freight")
                    .also {
                        manualFeeLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()
            }"

            // 应收金额
            manualTotal.text =
                obj.optNotNull("amountPayable")
                    .also {
                        mTotalEvent.value = it.doubleValue
                    }.formatDecimal()

            // 上期欠款
            manualBefore.text =
                obj.optNotNull("arrears")
                    .also {
                        manualBeforeLl.isVisible = it.doubleValue > 0.0
                    }.formatDecimal()

            // 上期欠票
            manualBefore1.text =
                obj.optNotNull("ticket")
                    .also {
                        manualBeforeLl1.isVisible = it.intValue > 0
                    }
        }
    }

}